﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Xc.Core.Tools;

namespace ExamSelfTouch.Tools
{
    public sealed class HttpBase2
    {
        public static string SESSION = string.Empty;

        private static readonly HttpClient client = new HttpClient();

        private HttpBase2() { }

        static HttpBase2() { }

        private static HttpClient GetHttpBase()
        {
            if (client == null || client.BaseAddress == null)
            {
                client.BaseAddress = new Uri(ConfigurationManager.AppSettings["LoginAddress"]);
                // Add an Accept header for JSON format.
                // 为JSON格式添加一个Accept报头
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
            }
            return client;
        }

        /// <summary>
        /// 异步Get请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<T> GetAsync<T>(string url) where T : class
        {
            try
            {
                HttpResponseMessage response = await GetHttpBase().GetAsync(url);  // Blocking call（阻塞调用）! 
                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsAsync<T>();
                    return data;
                }
                else
                {
                    LogTool.WriteErrorLog(string.Format("异步Post请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                    return null;
                }
            }
            catch (Exception ex)
            {
                LogTool.WriteErrorLog(ex);
                
                throw;
            }
           
        }

        /// <summary>
        /// 异步Post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static async Task<T> PostAsJsonAsync<T>(string url, object entity) where T : class
        {
            try
            {
                HttpResponseMessage response = await GetHttpBase().PostAsJsonAsync(url, entity);
                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsAsync<T>();
                    return data;
                }
                else
                {
                    LogTool.WriteErrorLog(string.Format("异步Post请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                    return null;
                }
            }
            catch (Exception ex)
            {
                LogTool.WriteErrorLog(ex);
                throw;
            }
        }
    }
}
